<template>
  <div class="div-e" v-loading="loading">
    <div class="in-t">
      <div class="in-ts"></div>
      <h3>{{isAdd ? "个人成交新增" : "个人成交修改"}}</h3>
    </div>
    <el-row>
      <el-col :span="20" :offset="2">
        <el-form :model="addOrUpdateForm" :rules="addOrUpdateFormRules" ref="addOrUpdateFormRefs" label-width="150px">
          <el-form-item  label="姓名" prop="name">
            <el-input v-model="addOrUpdateForm.name" placeholder="请填写姓名" @blur.once="confirmRepeatName"></el-input>
          </el-form-item>
          <el-form-item  label="联系人电话" prop="contactsMobile">
            <el-input v-model="addOrUpdateForm.contactsMobile" placeholder="请填写联系人手机或固定电话"></el-input>
          </el-form-item>
          <el-form-item  label="微信号" prop="">
            <el-input v-model="addOrUpdateForm.contactsWechat" placeholder="请填写联系人微信号"></el-input>
          </el-form-item>
          <el-form-item  label="身份证号" prop="contactsIdCard">
            <el-input v-model="addOrUpdateForm.contactsIdCard" placeholder="请填写身份证号码"></el-input>
          </el-form-item>
          <el-form-item  label="邮寄地址" prop="">
            <el-input v-model="addOrUpdateForm.mailingAddress" placeholder="请填写邮寄地址"></el-input>
          </el-form-item>
          <el-form-item label="所在地区" prop="areaId">
            <el-row>
              <el-col :span="4" >
                <el-select class="select-style" v-model="addOrUpdateForm.cityId"  placeholder="请选择城市" @change="changeCityOptions" @focus="getRegionalTree" clearable>
                  <el-option
                    v-for="item in cityOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
              </el-select>
              </el-col>
              <el-col :span="4" :offset="1">
                <el-select v-model="addOrUpdateForm.areaId"  placeholder="请选择地区" clearable>
                  <el-option
                    v-for="item in areaOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item  label="来源途径" prop="">
            <el-row>
              <el-col :span="4" >
                <el-select class="select-style"  v-model="addOrUpdateForm.originTag" type="textarea" placeholder="请选择来源途径" @focus="getOriginList" @clear="clearOrigin" clearable>
                  <el-option
                    v-for="item in originOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
              <el-col  :span="20" >
                <el-input v-if="isShowOriginRemarkInput " v-model="addOrUpdateForm.originRemark"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div class="button-group">
          <el-button @click="clickCancel">返回</el-button>
<!--          <el-button type="primary" @click="clickConfirm">保存</el-button>-->
          <el-button type="primary" @click="showCooperationDialog">保存</el-button>
        </div>
      </el-col>
    </el-row>
    <add-cooperation-dialog :dialog-visible="addCooperationDialogVisible" @dialogVisibleChange="cooperationDialogVisibleChange" @getCooperationData="setCooperationData"></add-cooperation-dialog>
  </div>
</template>

<script>
import {getOriginWay, checkRepeatName} from '../../../../../api/customer/personal'
import {identityCardValidator, mobileAndPhoneValidator} from '../../../../../utils/validate'
import {getDetail, saveCustomer, updateCustomer} from '../../../../../api/customer/customerDetail'
import {getRegionTree} from '../../../../../api/customer/region'
import {addCoopetationDialogMixin} from '../../../../../mixin/index'
import AddCooperationDialog from '../AddCooperationDialog'

export default {
  name: 'add-or-update',
  components: {AddCooperationDialog},
  mixins: [addCoopetationDialogMixin],
  props: {
    isAdd: {
      type: Boolean,
      default: true
    },
    id: {
      type: Number,
      default: null
    }
  },
  created () {
    this.getOriginList()
    this.getRegionalTree()
    if (!this.isAdd) {
      this.getDetail()
    }
  },
  watch: {
    // 主要用于修改时，获取并设置areaOptions
    'addOrUpdateForm.cityId': function (newValue, oldVal) {
      this.filterCityOptions(newValue)
    }
  },
  data () {
    return {
      loading: false,
      addOrUpdateForm: {
        name: '',
        contactsMobile: '',
        contactsWechat: '',
        mailingAddress: '',
        contactsIdCard: '',
        cityId: '',
        areaId: '',
        originRemark: '',
        originTag: '',
        cooperationInfo: {}
      },
      originOptions: [],
      addOrUpdateFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        areaId: [
          { required: true, message: '请选择城市区域', trigger: 'blur' }

        ],
        contactsMobile: [{validator: mobileAndPhoneValidator, trigger: 'blur'}],
        contactsIdCard: [{validator: identityCardValidator, trigger: 'blur'}]
      },
      cityOptions: [],
      areaOptions: []
    }
  },
  methods: {
    // 初始化表单
    initAddorUpdateForm () {
      Object.keys(this.addOrUpdateForm).forEach((key) => { this.addOrUpdateForm[key] = '' })
      this.$nextTick(() => {
        this.$refs.addOrUpdateFormRefs.clearValidate()
      })
    },
    clickCancel () {
      if (this.isAdd) {
        this.$parent.changeComponent('personal')
      } else {
        this.$parent.changeIsEditState(false)
      }
    },
    showCooperationDialog () {
      this.$refs.addOrUpdateFormRefs.validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            this.cooperationDialogVisibleChange(true)
          } else {
            this.clickConfirm()
          }
        } else {
          return false
        }
      })
    },
    setCooperationData (data) {
     // console.log('datass', data)
      let cooperationInfo = {
        'income': data.income,
        'incomeDate': data.incomeDate,
        'detail': data.incomeDetail,
        'fileName': data.fileName,
        'fileUrl': data.fileUrl,
        'perfor': data.perfor,
        'incomeAccountId': data.incomeAccountId,
        'incomeAccount': data.incomeAccount,
        'incomeDetailList': data.incomeDetailList
      }
      this.addOrUpdateForm['cooperationInfo'] = cooperationInfo
      this.clickConfirm()
    },
    clickConfirm () {
      this.$refs.addOrUpdateFormRefs.validate((valid) => {
        if (valid) {
          let dataForm = {
            'name': this.addOrUpdateForm.name,
            'contactsMobile': this.addOrUpdateForm.contactsMobile,
            'contactsWechat': this.addOrUpdateForm.contactsWechat,
            'mailingAddress': this.addOrUpdateForm.mailingAddress,
            'contactsIdCard': this.addOrUpdateForm.contactsIdCard,
            'cityId': this.addOrUpdateForm.cityId,
            'areaId': this.addOrUpdateForm.areaId,
            'originRemark': this.addOrUpdateForm.originRemark,
            'originTag': this.addOrUpdateForm.originTag,
            'cooperationInfo': this.addOrUpdateForm.cooperationInfo
          }
          this.loading = true
          if (this.isAdd) {
            dataForm.typeId = 1
            dataForm.enterpriseFlag = 0
            saveCustomer(dataForm,
              () => {
                this.$message.success('添加成功!')
                this.cooperationDialogVisibleChange(false)
                this.initAddorUpdateForm()
                this.loading = false
              }, () => {
                this.loading = false
              })
          } else {
            if (this.id) {
              dataForm.id = this.id
              updateCustomer(dataForm, () => {
                this.$message.success('修改成功!')
                this.loading = false
              }, () => {
                this.loading = false
              })
            }
          }
        } else {
          return false
        }
      })
    },
    clearOrigin () {
      // this.addOrUpdateForm.originTag = ''
    },
    getOriginList () {
      this.originOptions = getOriginWay()
    },
    // 获取城市列表
    getRegionalTree () {
      let dataForm = {'actionId': 1}
      getRegionTree(dataForm, (data) => { this.cityOptions = data.data })
    },
    changeCityOptions (cityId) {
      this.addOrUpdateForm.areaId = ''
      this.filterCityOptions(cityId)
    },
    filterCityOptions (cityId) {
      // eslint-disable-next-line no-unused-vars
      let city = []
      this.areaOptions = []
      city = this.cityOptions.filter(item => item.id === cityId)
      if (city.length > 0) {
        this.areaOptions = city[0].children
      }
    },
    // 获取用户信息
    getDetail () {
      if (this.id) {
        this.loading = true
        getDetail(this.id,
          (data) => {
            Object.keys(data.data).forEach((key) => {
              this.addOrUpdateForm[key] = data.data[key]
              this.loading = false
            }, () => {
              this.loading = false
            })
          })
      }
    },
    // 重名验证
    confirmRepeatName () {
      checkRepeatName({
        id: '',
        certificateCode: '',
        name: this.addOrUpdateForm.name
      },
        () => {},
        ({msg}) => {
          this.$confirm(`${msg}，请检查确认是否为同一人！`, '提示', {
            confirmButtonText: '继续添加',
            cancelButtonText: '取消添加',
            type: 'warning'
          }).then(() => {

          }).catch(() => {
            this.clickCancel()
          })
        })
    }
  },
  computed: {
    isShowOriginRemarkInput () {
      return this.addOrUpdateForm.originTag === 1 || this.addOrUpdateForm.originTag === 5
    }
  }
}
</script>

<style lang="less" scoped>
.div-e {
  width: 100%;
  background-color: #FFFFFF;
  padding: 15px;

}
.in-ts {
  width: 5px;
  height: 18px;
  float: left;
  margin-right: 8px;
  background: #6E92E9;
}

.in-t {
  margin-bottom: 15px;
}

.select-button-group{
  display: flex;
  .el-select{
    flex: 1;
    margin-right: 10px;
  }
}

.button-group{
  display: flex;
  justify-content: center;
}

.select-style{
  margin-right: 10px;
}

</style>
